package cn.wj.school.cloud.service;

import cn.wj.school.cloud.dao.SyLoginLogMapper;
import cn.wj.school.cloud.dto.PageResponse;
import cn.wj.school.cloud.dto.SyLoginLogDTO;
import cn.wj.school.cloud.dto.SySchoolDTO;
import cn.wj.school.cloud.dto.condition.LoginLogCondition;
import cn.wj.school.cloud.dto.condition.SchoolCondition;
import cn.wj.school.cloud.model.SyLoginLog;
import cn.wj.school.cloud.utils.BeanCopyUtil;
import cn.wj.school.cloud.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.Collections;
import java.util.Date;

/**
 * 登录日志服务
 */
@Service
public class LoginLogServiceImpl implements LoginLogService {

    @Autowired
    private SyLoginLogMapper logMapper;

    @Override
    public PageResponse<SyLoginLogDTO> getLoginLogsByCondition(LoginLogCondition condition) {
        if (condition == null) {
            condition = new LoginLogCondition();
        }
        long count = logMapper.countLoginLogs(condition);
        if (count > 0) {
            return new PageResponse(count,
                    BeanCopyUtil.genBeanList(logMapper.selectLoginLogs(condition), SyLoginLogDTO.class));
        }
        return new PageResponse(0, Collections.emptyList());
    }

    @Override
    public void saveLoginLog(SyLoginLogDTO log) {
        if (log != null) {
            logMapper.insert(BeanCopyUtil.genBean(log, SyLoginLog.class));
        }
    }

    @Override
    public void writeLogoutTime(Long logId) {
        if (logId != null) {
            SyLoginLog log = logMapper.selectByPrimaryKey(logId);
            SyLoginLog upLog = new SyLoginLog();
            upLog.setId(logId);
            upLog.setLogoutTime(new Date());
            Long second =  Duration.between(log.getLoginTime().toInstant(),
                    upLog.getLogoutTime().toInstant()).toMinutes();
            upLog.setTimes(second);
            logMapper.updateByPrimaryKeySelective(upLog);
        }
    }

    @Override
    public SyLoginLogDTO getCurrentLog(Long userId) {
        return BeanCopyUtil.genBean(logMapper.selectLastUserLog(userId), SyLoginLogDTO.class);
    }
}
